package user

import (
	"context"
	"strconv"

	"mall/common/moneyx"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserAccountLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetUserAccountLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserAccountLogic {
	return &GetUserAccountLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetUserAccountLogic) GetUserAccount(in *user.GetUserReq) (*user.TmpUserAccountInfo, error) {
	if in.UserId == nil || *in.UserId == 0 {
		return nil, resultx.StatusError(resultx.USER_ID_REQUIRED, "")
	}

	res, err := l.svcCtx.CurrentUser.FindOne(l.ctx, *in.UserId)
	if err != nil {
		return nil, err
	}

	accountFilterMap := make(map[string]map[string][]any)
	accountFilterMap[model.UserAccountColumns.UserID] = map[string][]any{
		"equalTo": []any{res.ID},
	}
	accountList, _, err := l.svcCtx.CurrentUser.GetAccountList(l.ctx, model.M{
		"pageSize": uint64(1),
	}, -1, accountFilterMap)
	if err != nil || len(accountList) == 0 {
		return nil, err
	}

	account := accountList[0]
	var availablePoint uint64
	if account.Point > 0 {
		availablePoint = uint64(account.Point)
		if availablePoint > account.FrozenPoint {
			availablePoint -= account.FrozenPoint
		} else {
			availablePoint = 0
		}
	}
	var availableBalance uint64
	if account.Balance > 0 {
		availableBalance = uint64(account.Balance)
		if availableBalance > account.FrozenBalance {
			availableBalance -= account.FrozenBalance
		} else {
			availableBalance = 0
		}
	}

	return &user.TmpUserAccountInfo{
		UserId:           pointy.GetPointer(strconv.FormatUint(account.UserID, 10)),
		Password:         &account.Password,
		Point:            &account.Point,
		FrozenPoint:      &account.FrozenPoint,
		AvailablePoint:   pointy.GetPointer(availablePoint),
		HistoryPoint:     &account.HistoryPoint,
		Balance:          pointy.GetPointer(moneyx.FormatGem(account.Balance)),
		FrozenBalance:    pointy.GetPointer(moneyx.FormatGem(int64(account.FrozenBalance))),
		AvailableBalance: pointy.GetPointer(moneyx.FormatGem(int64(availableBalance))),
		RankId:           pointy.GetPointer(uint64(account.RankID)),
		// Loan:             &account.Loan,
		Credit: &account.Credit,
	}, nil
}
